from rest_framework.response import Response
from apps.UserControl.models.user import *
from apps.UserControl.serializrs import *
from apps.UserControl.permission import get_permission_list
from utils.response import SuccessResponse
from utils.viewsets import ModelViewSet
from rest_framework.generics import GenericAPIView
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
import logging
from djangoProject import settings
from apps.UserControl.filters.user import UserFilters

logger = logging.getLogger('log')


class UserModelViewSet(ModelViewSet):
    queryset = User.objects.filter(is_delete=False)
    serializer_class = UserSerializers
    filter_class = UserFilters

    @action(methods=['get'], detail=False, url_name='info', permission_classes=[IsAuthenticated])
    def info(self, request, pk=None):
        user = request.user
        perms = get_permission_list(user)
        portrait = None
        try:
            portrait = "http://www.testering.xyz" + user.portrait.url
        except Exception as e:
            print(e)
        data = {
            'id': user.id,
            'username': user.username,
            'name': user.name,
            # 'roles': user.roles.values_list('name', flat=True),
            'portrait': portrait,
            'perms': perms,
        }
        return Response(data)


class UploadAPIView(GenericAPIView):
    """
    上传头像
    """
    queryset = User.objects.filter(is_delete=False)
    serializer_class = UserSerializers

    def post(self, request, *args, **kwargs):
        if request.method == 'POST':
            # user_id = request.data.get('user_id')
            # User.objects.filter(id=user_id).update(request.FILES.get('portrait'))
            img = request.FILES.get('file')
            path = settings.MEDIA_ROOT + '/portrait/'

            with open(path + f'{img.name}', 'wb+') as f:
                for chunk in img.chunks():
                    f.write(chunk)

            user_id = request.data.get('user_id')
            # if User.objects.filter(id=user_id) not
            User.objects.filter(id=user_id).update(portrait='portrait/' + img.name)
            data = "http://www.testering.xyz" + settings.MEDIA_URL + 'portrait/' + img.name,

        return SuccessResponse(data={'data': data}, msg='上传成功！')
